<template>
  <div>
    <h1>添加业主</h1>
    <el-row>
      <el-col :span="21" :offset="1">
        <el-form :model="ownerForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
          <el-row>
            <el-col :span="8">
              <el-form-item sty label="姓名：" prop="name">
                <el-input v-model="ownerForm.name"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="身份证号：" prop="card">
                <el-input v-model="ownerForm.card"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <el-form-item label="购房时间：" prop="buyTime">
                <el-date-picker
                    v-model="ownerForm.buyTime"
                    type="date"
                    placeholder="选择日期">
                </el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>


          <el-row>
            <el-col :span="8">
              <el-form-item label="联系电话1：" prop="phone1">
                <el-input v-model="ownerForm.phone1"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8" >
              <el-form-item label="联系电话2：">
                <el-input v-model="ownerForm.phone2"></el-input>
              </el-form-item>
            </el-col>

            <el-col :span="7">
              <el-form-item label="籍贯：" prop="nativePlace">
                <el-input v-model="ownerForm.nativePlace"></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="24">
            <el-col :span="4">
              <el-form-item label="住址：" prop="buildingId">
                <el-select style="width: 120px" v-model="ownerForm.buildingId" @change="selectAllUnit()"
                           placeholder="请选择楼栋">
                  <el-option
                      v-for="building in building"
                      :key="building.id"
                      :label="building.buildingName"
                      :value="building.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item label-width="62px" prop="unitId">
                <el-select style="width: 130px" v-model="ownerForm.unitId" placeholder="请选择单元号" @change="selectHouseByUnit()">
                  <el-option
                      v-for="item in unit"
                      :key="item.id"
                      :label="item.unitName"
                      :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item label-width="30px" prop="houseId">
                <el-select style="width: 130px" v-model="ownerForm.houseId" placeholder="请选择门牌号">
                  <el-option
                      v-for="item in house"
                      :key="item.id"
                      :label="item.houseNumber"
                      :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="6">
              <el-form-item label="是否在此居住：" label-width="110px">
                <el-radio v-model="ownerForm.liveing" label="1">是</el-radio>
                <el-radio v-model="ownerForm.liveing" label="0">否</el-radio>
              </el-form-item>
            </el-col>

          </el-row>

          <el-row>
            <el-col :span="5">
              <el-form-item label="紧急联系人：">
                <el-input v-model="ownerForm.emergencyPerson"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="5" :offset="1">
              <el-form-item label="紧急电话1：">
                <el-input v-model="ownerForm.emergencyPhone"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="5" :offset="1">
              <el-form-item label="紧急电话2：">
                <el-input v-model="ownerForm.emergencyPhone2"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="邮箱：">
                <el-input v-model="ownerForm.email"></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="8">
              <el-form-item label="身份证正面照片：" label-width="85px">
                <el-upload
                    class="upload-demo"
                    :headers="manageToken"
                    action="http://localhost:8080/manage/uploadCardPicFacade"
                    :on-success="handleCardFacadeSuccess"
                    :on-remove="handleRemove"
                    :file-list="cardFileList"
                    :before-upload="beforeUpload"
                    list-type="picture">
                  <el-button size="small" type="primary">点击上传</el-button>
                  <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
                </el-upload>
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <el-form-item label="身份证反面照片：" label-width="85px">
                <el-upload
                    class="upload-demo"
                    :headers="manageToken"
                    action="http://localhost:8080/manage/uploadCardPicBack"
                    :on-success="handleCardBackSuccess"
                    :on-remove="handleRemove"
                    :file-list="cardFileList"
                    :before-upload="beforeUpload"
                    list-type="picture">
                  <el-button size="small" type="primary">点击上传</el-button>
                  <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
                </el-upload>
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <el-form-item label="业主照片：" label-width="85px">
                <el-upload
                    class="upload-demo"
                    :headers="manageToken"
                    action="http://localhost:8080/manage/uploadPic"
                    :on-success="handlePictureSuccess"
                    :on-remove="handleRemove"
                    :file-list="cardFileList"
                    :before-upload="beforeUpload"
                    list-type="picture">
                  <el-button size="small" type="primary">点击上传</el-button>
                  <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
                </el-upload>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="8" :offset="7">
              <el-form-item>
                <el-button type="primary" @click="submitForm('ruleForm')">立即创建</el-button>
                &nbsp;
                <el-button @click="resetForm('ruleForm')">重置</el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>

      </el-col>
    </el-row>
  </div>
</template>

<style>

</style>
<script>
export default {
  data() {
    return {
      ownerForm: {
        id: '',
        name: '',
        card: '',
        cardPicFacade: '',//身份证正面
        cardPicBack: '',//身份证反面
        picture: '',
        phone1: '',
        phone2: '',
        emergencyPerson: '',
        emergencyPhone: '',
        emergencyPhone2: '',
        nativePlace: '',
        buyTime: '',
        staffId: '',
        liveing: '1',
        email: '',

        buildingId: '',
        unitId: '',
        houseId:'',
      },
      manageToken: {
        manageToken: window.localStorage.getItem("manageToken")
      },
      staff: JSON.parse(window.localStorage.getItem("admin")),
      building: [],
      unit: [],
      house:[],
      uploadAction: null,
      cardFileList: [],
      allowedExts: ".jpg,.png",
      imgUrl: '',
      rules: {
        name: [
          {required: true, message: '请输入姓名', trigger: 'blur'},
          {min: 2, max: 5, message: '长度在 2 到 5 个字符', trigger: 'blur'}
        ],
        card: [
          {required: true, message: '请输入身份证', trigger: 'blur'}
        ],
        buyTime: [
          {type: 'date', required: true, message: '请选择日期', trigger: 'blur'}
        ],
        phone1: [
          {required: true, message: '请选择手机号', trigger: 'blur'}
        ],
        buildingId: [
          {required: true, message: '请选择楼栋', trigger: 'blur'}
        ],
        unitId: [
          {required: true, message: '请选择单元', trigger: 'blur'}
        ],
        houseId:[
          {required: true,message:'请选择门牌号',trigger:'blur'}
        ],
        nativePlace: [
          {required: true, message: '请填写籍贯', trigger: 'blur'}
        ],
        personSize: [
          {required: true, message: '请填写人数', trigger: 'blur'}
        ]

      }
    };
  },
  created() {
    this.selectAllBuilding();
  },
  methods: {
    selectAllBuilding() {
      this.$axios.get("manage/selectAllBuilding")
          .then(response => {
            this.building = response.data.data;
          })
    },

    selectAllUnit() {
      this.ownerForm.unitId = '';
      this.ownerForm.houseId='';
      this.unit='';
      this.house='';
      console.log(this.unit);
      this.$axios.get("manage/unit/selectUnitById", {params: {id: this.ownerForm.buildingId}})
          .then(response => {
            this.unit = response.data.data;
          })
    },
    selectHouseByUnit(){
      this.ownerForm.houseId='';
      this.house='';
      this.$axios.get("manage/selectHouseByUnit",{params:{unitId:this.ownerForm.unitId}})
          .then(response=>{
            this.house = response.data.data;
          })
    },

    submitForm(formName) {
      this.ownerForm.staffId = this.staff.id;
      console.log(this.ownerForm);
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$axios.post("manage/insertOwner", this.ownerForm)
              .then(response => {
                this.$message({
                  showClose: true,
                  message: '添加成功',
                  type: 'success',
                });
                this.resetForm();
              })
        } else {
          this.$message({
            showClose: true,
            message: '错误！有信息未填写',
            type: 'error',
          });
          return false;
        }
      });
    },
    resetForm(formName) {
      Object.assign(this.$data.ownerForm, this.$options.data().ownerForm);
      this.$refs.ruleForm.clearValidate();
      // this.$refs[formName].resetFields();
      // this.$refs[formName].resetFields();
    },
    handleRemove() {
    },
    handleCardFacadeSuccess(res, file) {
      console.log(res);
      console.log(file);
      this.ownerForm.cardPicFacade = res.fileName;
      console.log(this.ownerForm.picture)
    },
    handleCardBackSuccess(res, file) {
      this.ownerForm.cardPicBack = res.fileName;
    },
    handlePictureSuccess(res, file) {
      this.ownerForm.picture = res.fileName;
    },
    beforeUpload(file) {
      let dotIndex = file.name.lastIndexOf(".");

      if (dotIndex == -1) {
        this.$message.error('只能上传图片(' + this.allowedExts + ')');
        return false;
      }
      //扩展名
      let ext = file.name.substring(dotIndex);
      if (!("," + this.allowedExts + ",").includes("," + ext + ",")) {
        this.$message.error('只能上传图片(' + this.allowedExts + ')');
        return false;
      }

      const isLt2M = file.size / 1024 / 1024 < 2;

      if (file.size > 1024 * 1024 * 2) {
        this.$message.error('上传头像图片大小不能超过 2M!');
        return false;
      }
      return true;
    }
  }
}
</script>
